<?php
jimport('joomla.application.component.controller');

class bgController extends JController {
    
    public $_tbl = null;
    
    public function __construct(){
    
        JRequest::setVar('cate', JRequest::getVar('cate', 'inbox'));
        //$cid = JRequest::getVar('cid');
        $cid = JRequest::getVar('cid', null);
        
        if(in_array(JRequest::getVar('task'), array('view', 'reply', 'forward'))){
            $cid = explode('_', strtolower($cid[0]));
            JRequest::setVar('cid', $cid[1]);
            JRequest::setVar('tbl', $cid[0]);
        }
     
        parent::__construct();
        $this->model = new bgModelbg();
        $this->model->_username = JFactory::getUser()->username;
    }
    
    public function display(){
        
        parent::display();
    }
    
    public function searchtitle(){
    
    	JRequest::setVar('jsearch', array());
        JRequest::setVar('task', null);
        parent::display();
    }

    public function search(){
    	JRequest::setVar('title_search', null);
        //JRequest::setVar('limitstart', 0);
        parent::display();
    }
    
    public function save(){
        $post = JRequest::getVar('jform');
        
        $user = JFactory::getUser();

        $data['USEM_CODE']        = $user->username;
    	$data['TITLE']            = $post['TITLE'];
    	$data['BODY']             = $post['BODY'];
    	$data['DATE']             = date('Y-m-d h:i:s');
    	$data['OCBA_CODE_LIST']   = $post['OCBA_CODE_LIST'];
        
        $attachments_encode = json_decode(JRequest::getVar('attachment'), true);

        if(JRequest::getVar('type') == 'forward'){
            
            // phan tich ng nhan duoc
            $recipient = explode(';', $data['OCBA_CODE_LIST']);
            foreach($recipient as $re){
                if($re){
                    $group = $re; 
                    
                    $re = substr($re, strpos($re,'(')); 
                    $re = str_replace(')', '', $re);
                    $re = str_replace('(', '', $re);
                    //$data['OCBA_CODE_LIST'] = str_replace('(', '', $data['OCBA_CODE_LIST']);
                    
                    if(substr($group, 0, 1) == '*'){ // group mail
                        
                    }else{ // list user mail
                        
                    }
                
                }
            }
            // gan dinh kem mac dinh
            foreach($attachments_encode as $att=>$rec){
                $attachments_encode[$att] = 'U_'.$data['OCBA_CODE_LIST'];
            }
        }

        $attachments = $attachments_encode;
       
        $recipients = null;
        if($attachments){
            // chuyen attachment ve dang user lam khoa
            foreach($attachments as $att=>$rec){
                $recs = explode(',', $rec);
                foreach($recs as $rec){
                    $info = explode('_', $rec);
                    if($info[0] == 'U'){ // user
                        $recipients[$info[1]][] = $att;
                    }else{ // group
                        $usersGroup = $this->model->getUserSystem($info[1]);
                        foreach($usersGroup as $u){
                            $recipients[$u['username']][] = $att;
                        }// end foreach user in group
                    }
                } // end foreach recipient
            }// end foreach attachment
        }
        
        
        if(JRequest::getVar('cate') == 'folder' || JRequest::getVar('cate') == 'search'){
            $cid = explode('_', JRequest::getVar('cid'));
            $this->_tbl = $cid[0];
            $cid = $cid[1];
        }else{
            $cid = JRequest::getVar('cid');
        }
        
        // change flag reply to 1
        if(JRequest::getVar('type') == 'reply'){
            $this->model->setReply($cid, $this->getTable());
        }
        
        // change flag forward to 1
        if(JRequest::getVar('type') == 'forward'){
            $this->model->setForward($cid, $this->getTable());
        }
        
        // insert and get id message sent
    	$id_sent = $this->model->addMessageSend($data, mysql_escape_string(json_encode($attachments_encode)));
        $data['MESE_CODE'] = $id_sent;
        $this->model->addMessageRecipient($data, $recipients);
        
        // if this is message draft, it were deleted after it sent
        if(JRequest::getVar('cate') == 'draft' && JRequest::getVar('cid') != null){
            $this->model->deleteMessageForever(JRequest::getVar('cid'), 'MESE');
        }
        
        $this->setRedirect('index.php?top=page&option=com_frmessage&cate='.JRequest::getVar('cate','inbox'));
       // $this->setRedirect('index.php?top=page&option=com_frmessage&cate=inbox');
    }

    public function savetemp(){
    	$post = JRequest::getVar('jform');
        
        $user = JFactory::getUser();

        $data['USEM_CODE']        = $user->username;
    	$data['TITLE']            = $post['TITLE'];
    	$data['BODY']             = $post['BODY'];
    	$data['DATE']             = date('Y-m-d h:i:s');
    	$data['OCBA_CODE_LIST']   = $post['OCBA_CODE_LIST'];
        
        $attachments_encode = JRequest::getVar('attachment');
        
    	$this->model->addMessageDraft($data, mysql_escape_string($attachments_encode));
        $this->setRedirect('index.php?top=page&option=com_frmessage&cate='.JRequest::getVar('cate','inbox'));
    }
    
    public function delete(){
    	$ids = JRequest::getVar('cid', array());
        $cate = JRequest::getVar('cate');
        
        switch($cate){

            case 'search':
                JRequest::setVar('task', 'search');
                foreach($id as $i){
                    $mes = explode('_', $i);
                    $this->model->deleteMessageForever($mes[1], strtoupper($mes[0]));
                }
                
                // sau khi xoa o search bang link nhan o xem chi tiet
                // ta chuyen ve inbox
                if(!JRequest::getVar('jsearch')){
                    $this->setRedirect('index.php?top=page&option=com_frmessage&cate=inbox');
                }
            break;
            case 'folder':
                foreach($ids as $i){
                    $i = explode('_', $i);
                    $this->model->deleteMessage($i[1], strtoupper($i[0]));
                }
               
                // set lai gia tri id folder, tai thu muc folder hien tai
                $this->setRedirect('index.php?top=page&option=com_frmessage&cate='.$cate.'&id='.JRequest::getVar('id'));
            break;
            
            case 'inbox':
            case 'sent':
                foreach($ids as $i){
                    $i = explode('_', $i);
                    $this->model->deleteMessage($i[1], strtoupper($i[0]));
                }
                $this->setRedirect('index.php?top=page&option=com_frmessage&cate='.$cate);
            break;
            
            case 'draft':
            case 'trash':
                foreach($ids as $i){
                    $i = explode('_', $i);
                    $this->model->deleteMessageForever($i[1],  strtoupper($i[0]));
                }
                $this->setRedirect('index.php?top=page&option=com_frmessage&cate='.$cate);
            break;
        }
        
        
        parent::display();
    }
    
    public function reply(){
        JRequest::setVar('noHead', true);   // delete librarie mootol joomla      
        $cid = JRequest::getVar('cid');  
    	if(!$cid){
    	   $this->setRedirect('index.php?'.$_SERVER['QUERY_STRING']);
    	}else{
    	   // neu la folder, set lai cac gia tri id loai bo 5 ky tu dau mere, cate tuong ung
    	   /*if(substr($cid[0],0,4) == 'mere'){
    	       JRequest::setVar('cid',array(substr($cid[0],5)));
    	       JRequest::setVar('cate','inbox');
    	   }
           
           if(substr($cid[0],0,4) == 'mese'){
    	       JRequest::setVar('cid',array(substr($cid[0],5)));
    	       JRequest::setVar('cate','sent');
    	   }*/
    	}
        parent::display();
    }
    
    public function forward(){
        JRequest::setVar('noHead', true); // delete librarie mootol joomla 
        $cid = JRequest::getVar('cid');       
    	if(!$cid){
    	   $this->setRedirect('index.php?'.$_SERVER['QUERY_STRING']);
    	}else{
    	   // neu la folder, set lai cac gia tri id loai bo 5 ky tu dau mere, cate tuong ung
    	   if(substr($cid[0],0,4) == 'mere'){
    	       JRequest::setVar('cid',array(substr($cid[0],5)));
    	       JRequest::setVar('cate','inbox');
    	   }
           
           if(substr($cid[0],0,4) == 'mese'){
    	       JRequest::setVar('cid',array(substr($cid[0],5)));
    	       JRequest::setVar('cate','sent');
    	   }
    	}
        
        parent::display();
    }
    
    public function folders(){
       
        $ids = JRequest::getVar('cid', array());
        foreach($ids as $id){
            $id = explode('_', $id);
            $this->model->setFolder($id[1], $id[0], JRequest::getVar('folders'));
        }
        parent::display();
    }
    
    public function getTable(){
        
        if(!$this->_tbl){
        	$cate = JRequest::getVar('cate');
            switch($cate){
                case 'trash':
                case 'inbox':
                    $this->_tbl = 'mere';
                break;
                case 'draft':
                case 'sent':
                    $this->_tbl = 'mese';
                break;
            }
        }
        return $this->_tbl;
    }
    
    public function emptyTrash(){
    	$this->model->emptyTrash();
        $this->setRedirect('index.php?top=page&option=com_frmessage&cate=trash');
    }
    
    
}
